<script setup lang="ts">
import { User, Lock } from "@element-plus/icons-vue";
import { reactive, ref, onMounted, watch } from "vue";
import { useRouter } from "vue-router";
import useUserStore from "@/store/modules/user";
let useStore = useUserStore();
import { ElMessageBox, ElNotification, ElMessage } from "element-plus";
import { getTime } from "@/utils/time";
// @ts-ignore
import sha256 from "sha256"; // 导入哈希函数库
let Router = useRouter();

let loginForm = reactive({ username: "", password: "" });
let ruleloginFormRef = ref();
let hashedPassword = ref(""); // 这里将保存哈希后的密码
const loading = ref(false);
const login = async () => {
  try {
    await ruleloginFormRef.value.validate();
    loading.value = true;
    hashedPassword.value = sha256(loginForm.password);

    try {
      let Form = {
        username: loginForm.username,
        password: hashedPassword.value,
      };
      const jsonString = JSON.stringify(Form);
      await useStore.UserLogin(jsonString as any);
      await useStore.userInfo();
      Router.push("/home");
      if (useStore.user.roles.includes("LIBRARY_ROOT")) {
        Router.push("/home");
      } else if (useStore.user.roles.includes("ADMIN")) {
        Router.push("/home");
      } else {
        Router.push("/config/book");
      }

      ElNotification({
        title: `HI,${getTime()}好`,
        message: "欢迎登录逸图智控平台",
        type: "success",
      });
      setTimeout(() => {
        if (useStore.user.isTempUser == 1) {
          ElMessageBox.alert(
            `用户将在${useStore.user.expireTime}到期`,
            "到期提醒",
            {
              confirmButtonText: "OK",
              callback: () => {
                useStore.user.isTempUser == 2;
              },
            }
          );
        }
      }, 1000);

      loading.value = false;
    } catch (error) {
      loading.value = false;
      //console.log(error);
      ElNotification({
        // title: "欢迎登录智能盘点大数据处理系统",
        message: (error as Error).message,
        type: "error",
      });
    }
  } catch (error) {
    loading.value = false;

    // ElMessage.error("登录失败");
  }
};
const rules = {
  username: [
    { required: true, message: "用户不能为空", trigger: ["blur", "change"] },
    { min: 1, max: 20, message: "账号长度过长", trigger: ["blur", "change"] },
  ],
  password: [
    { required: true, message: "密码不能为空", trigger: ["blur", "change"] },
    {
      min: 8,
      max: 15,
      message: "密码长度至少8位",
      trigger: ["blur", "change"],
    },
  ],
};

const displayedPassword = ref(""); // 显示在输入框中的密码（星号）

// 监视实际密码的变化，并更新显示的密码
watch(displayedPassword, (newValue, oldValue) => {
  if (newValue.length > oldValue.length) {
    // 如果新值比旧值长，说明是新增字符
    loginForm.password += newValue[newValue.length - 1];
  } else {
    // 否则是删除字符
    loginForm.password = loginForm.password.slice(0, newValue.length);
  }

  // 将显示的密码更新为相应数量的星号
  displayedPassword.value = "*".repeat(loginForm.password.length);
});

const handleInput = () => {
  // 处理输入事件
  // console.log("Password:", loginForm.password);
};
onMounted(() => {
  getTime();
});
</script>

<template>
  <div class="login-container">
    <el-form
      class="login-form"
      ref="ruleloginFormRef"
      :model="loginForm"
      :rules="rules"
    >
      <span
        style="
          color: #fff;
          font-size: 25px;
          display: block;
          margin-bottom: 15px;
          text-align: center;
        "
        >逸图智控平台</span
      >
      <el-form-item prop="username"
        ><el-input
          clearable
          :prefix-icon="User"
          size="large"
          v-model="loginForm.username"
        ></el-input
      ></el-form-item>
      <el-form-item prop="password">
        <el-input
          maxlength="8"
          clearable
          :prefix-icon="Lock"
          size="large"
          type="text"
          v-model="displayedPassword"
          @input="handleInput"
          @keyup.enter="login"
        >
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          :loading="loading"
          style="width: 100%"
          type="primary"
          size="default"
          @click="login"
          >登录</el-button
        ></el-form-item
      >
    </el-form>
  </div>
</template>

<style lang="scss" scoped>
.el-notification {
  z-index: 9999; /* 根据需要设置一个合适的 z-index 值 */
}
.login-container {
  width: 100%;
  min-height: 100%;
  overflow: hidden;
  background-color: #2d3a4b;
  display: flex;
  justify-content: center;

  .login-form {
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }
  .el-form-item {
    background: rgb(0 0 0 / 10%);
    border: 1px solid rgb(255 255 255 / 10%);
    border-radius: 5px;
  }

  .el-input {
    padding-left: 10px;
    height: 45px;
    background: transparent;

    // 子组件 scoped 无效，使用 :deep
    :deep(.el-input__wrapper) {
      padding: 0;
      background: transparent;
      box-shadow: none;
      .el-input__prefix-inner {
        color: #fff;
        padding-right: 2px;
      }
      .el-input__suffix-inner {
        color: #fff;
        padding-right: 10px;
      }

      .el-input__inner {
        color: #fff;
        caret-color: #fff;
        background: transparent;
        border: 0;
        border-radius: 0;

        &:-webkit-autofill {
          box-shadow: 0 0 0 1000px transparent inset !important;
          -webkit-text-fill-color: #fff !important;
        }

        // 设置输入框自动填充的延迟属性
        &:-webkit-autofill,
        &:-webkit-autofill:hover,
        &:-webkit-autofill:focus,
        &:-webkit-autofill:active {
          transition:
            color 99999s ease-out,
            background-color 99999s ease-out;
          transition-delay: 99999s;
        }
      }
    }
  }
}
</style>
